import React, { useState, useEffect, useRef, useContext } from "react";
import { Table, Button, Modal, Form, Input } from "antd";
import { DeleteOutlined, ExclamationCircleOutlined } from "@ant-design/icons";

import axios from "axios";
const { confirm } = Modal;
export default function NewsCategory() {
  const [data, setData] = useState([]);
  const EditableContext = React.createContext(null); //使用表格可编辑的话 需要先创建一个上下文对象
  // 获取所有权限
  useEffect(() => {
    axios.get("/categories").then((res) => {
      let list = res.data;
      console.log(list);
      setData(list);
    });
  }, []);
  // 表格头设置
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      render: (id) => <b>{id}</b>,
    },
    {
      title: "栏目名称",
      dataIndex: "label",
      // 让哪项可编辑就添加这个函数
      onCell: (record) => ({
        record,
        editable: true,
        dataIndex: "label",
        title: "栏目名称",
        handleSave: handleSave,
      }),
    },

    {
      title: "操作",
      render: (row) => {
        return (
          <div>
            <Button
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => confirmMethod(row)}
            />
          </div>
        );
      },
    },
  ];
  // 点击编辑的完的回调函数
  const handleSave = (record) => {
    // record就是修改过后的对象
    console.log(record.id);
    data.forEach((item) => {
      console.log(item.id);
    });
    setData(
      data.map((item) => {
        // 如果是这一项的话就返回特定的内容
        if (item.id === record.id) {
          return {
            id: record.id,
            label: record.label,
            value: record.label,
          };
        }
        // 如果不是当前的这一项直接返回原来的
        return item;
      })
    );
    // 最后带着修改完的参数在向服务器发送请求
    axios.patch(`/categories/${record.id}`, {
      label: record.label,
      value: record.label,
    });
  };
  // 删除事件
  function confirmMethod(row) {
    confirm({
      title: "你确定删除当前项吗？",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        setData(data.filter((item) => item.id !== row.id));
        axios.delete(`/categories/${row.id}`);
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  }
  // 可编辑的row回调函数
  const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };
  // 可编辑的列回调函数
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current.focus();
      }
    }, [editing]);
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };
    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({
          ...record,
          ...values,
        });
      } catch (errInfo) {
        console.log("Save failed:", errInfo);
      }
    };
    let childNode = children;
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
    return <td {...restProps}>{childNode}</td>;
  };
  return (
    <Table
      pagination={{ pageSize: 5 }}
      columns={columns}
      dataSource={data}
      rowKey={(item) => item.id}
      // 自定组件 让一个表格变成编辑的
      components={{
        body: {
          row: EditableRow, //可编辑的row
          cell: EditableCell, //可编辑的列
        },
      }}
    />
  );
}
